package com.cy.store11.controller;

import com.cy.store11.controller.ex.*;
import com.cy.store11.controller.ex.FileEmptyException;
import com.cy.store11.service.ex.*;
import com.cy.store11.util.JsonResult;
//import org.apache.tomcat.util.http.fileupload.FileUploadException;
import org.springframework.web.bind.annotation.ExceptionHandler;

import javax.servlet.http.HttpSession;

//控制层类的基类
public class BaseController {

    /** 操作成功的状态码 */
    public static final int OK = 200;
    /** 请求处理方法：这个方法的返回值就是需要传递给全端的数据*/
    @ExceptionHandler({ServiceException.class, FileUploadException.class})
    public JsonResult<Void> handleException(Throwable e){ //用于统一处理抛出的异常
            JsonResult<Void> result = new JsonResult<>();
            if(e instanceof UsernameDuplicatedException){
                result.setState(4000);
                result.setMessage("用户名已经被占用");
            }
            else if (e instanceof InsertException){
                result.setState(5000);
                result.setMessage("注册时产生未知异常");
            }
            else if(e instanceof UsernameNotFoundException){
                result.setState(5001);
                result.setMessage("用户数据不存在的异常");
            }
            else if(e instanceof PasswordNotMatchException){
                result.setState(5002);
                result.setMessage("用户的密码错误");
            }
            else if(e instanceof UpdateException){
                result.setState(5001);
                result.setMessage("更新错误");
            }
            else if(e instanceof FileEmptyException){
                result.setState(6000);
            }
            else if(e instanceof FileSizeException){
                result.setState(6001);
            }
            else if(e instanceof FileStateException){
                result.setState(6002);
            }
            else if(e instanceof FileTypeException){
                result.setState(6003);
            }
            else if(e instanceof FileUploadIOException){
                result.setState(6004);
            }
            return result;
    }

    /**
     *获取session对象中的uid
     * @param session session对象
     * @return 当前登录用户的uid
     */
    protected final Integer getuidFromSession(HttpSession session){
        return Integer.valueOf(session.getAttribute("uid").toString());
    }

    /**
     *获取session对象中的username
     * @param session session对象
     * @return 当前登录用户的username
     */
    protected final String getUsernameFromSession(HttpSession session){
        return session.getAttribute("username").toString();
    }
}
